<script setup>
import { nextTick, ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { userinfo } from "@/services/user";
import { base_URL } from "@/utils/http";
import { userauth, selectbankList } from "@/services/reward";
import { thirdPartySignApi, getAuthApi } from "@/services/reward";

onShow(async () => {
  await getAuthFun();
  await userinfofun();
});
// onLoad(() => {
//   userinfofun();
// });
const isphone = ref(false);
const isname = ref(false);
const isidcard = ref(false);

const userobj = ref({});
async function userinfofun() {
  let res = await userinfo();
  userobj.value = res.data;
  if (userobj.value && userobj.value.phone) {
    isphone.value = true;
  }
  if (
    (userobj.value && userobj.value.name) ||
    (authObj.value && authObj.value.name)
  ) {
    isname.value = true;
  }
  if (userobj.value && userobj.value.idcard) {
    isidcard.value = true;
  }
  fromdate.value.phone =
    authObj.value && authObj.value.phone
      ? authObj.value.phone
      : userobj.value && userobj.value.phone
      ? userobj.value.phone
      : fromdate.value.phone;

  fromdate.value.name =
    authObj.value && authObj.value.name
      ? authObj.value.name
      : userobj.value && userobj.value.name
      ? userobj.value.name
      : fromdate.value.name;
}

const fromdate = ref({
  name: "",
  phone: "",
  card_sn: "",
});
const rules = ref({
  name: {
    type: "string",
    required: true,
    message: "请填写姓名",
    trigger: ["blur", "change"],
  },
  phone: {
    type: "string",
    required: true,
    len: 11,
    message: "请输入11位数手机号",
    trigger: ["blur", "change"],
  },
  card_sn: {
    type: "string",
    required: true,
    len: 18,
    message: "请输入18位数的身份证",
    trigger: ["blur", "change"],
  },
  bank: {
    type: "string",
    required: true,
    trigger: ["blur", "change"],
    message: "请输入选择开户行",
  },
  open_bank: {
    type: "string",
    required: true,
    trigger: ["blur", "change"],
    message: "请输入支行信息",
  },
  bank_sn: {
    type: "string",
    required: true,
    message: "请输入银行卡号",
    trigger: ["blur", "change"],
  },
  ali: {
    type: "string",
    required: true,
    message: "请输入支付宝账号",
    trigger: ["blur", "change"],
  },
});

const fileList1 = ref([]);
const fileList2 = ref([]);
const fileList3 = ref([]);

//上传图片
// 删除图片
const deletePic1 = (event, type) => {
  let fileList = [];

  fileList = fileList1.value;

  fileList.splice(event.index, 1);
};
const afterRead1 = async (event, type) => {
  let fileListLen = 0;
  let filelist = [];
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

  fileListLen = fileList1.value.length;
  filelist = fileList1.value;

  let lists = [].concat(event.file);
  lists.map((item) => {
    filelist.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });

  // return;
  for (let i = 0; i < lists.length; i++) {
    uni.uploadFile({
      url: base_URL + "/api/upload/file",
      filePath: lists[i].url,
      name: "file",
      formData: {
        user: "test",
      },
      header: {
        Authorization: uni.getStorageSync("Authorization"),
      },
      success: async (uploadFileRes) => {
        let data = JSON.parse(uploadFileRes.data);
        if (data.code == 200) {
          filelist.splice(fileListLen, 1, {
            ...item,
            status: "success",
            message: "",
            url: data.data.url,
          });
          fileListLen++;
        }
      },
      fail: function (e) {
        uni.hideLoading();
      },
    });

    let item = fileList1.value[fileListLen];
  }
};
const deletePic2 = (event, type) => {
  let fileList = [];

  fileList = fileList2.value;

  fileList.splice(event.index, 1);
};
const afterRead2 = async (event, type) => {
  let fileListLen = 0;
  let filelist = [];
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

  fileListLen = fileList2.value.length;
  filelist = fileList2.value;

  let lists = [].concat(event.file);
  lists.map((item) => {
    filelist.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });

  // return;
  for (let i = 0; i < lists.length; i++) {
    uni.uploadFile({
      url: base_URL + "/api/upload/file",
      filePath: lists[i].url,
      name: "file",
      formData: {
        user: "test",
      },
      header: {
        Authorization: uni.getStorageSync("Authorization"),
      },
      success: async (uploadFileRes) => {
        let data = JSON.parse(uploadFileRes.data);
        if (data.code == 200) {
          filelist.splice(fileListLen, 1, {
            ...item,
            status: "success",
            message: "",
            url: data.data.url,
          });
          fileListLen++;
        }
      },
      fail: function (e) {
        uni.hideLoading();
      },
    });

    let item = fileList2.value[fileListLen];
  }
};
const deletePic3 = (event, type) => {
  let fileList = [];

  fileList = fileList3.value;

  fileList.splice(event.index, 1);
};
const afterRead3 = async (event, type) => {
  let fileListLen = 0;
  let filelist = [];
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

  fileListLen = fileList3.value.length;
  filelist = fileList3.value;

  let lists = [].concat(event.file);
  lists.map((item) => {
    filelist.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });

  // return;
  for (let i = 0; i < lists.length; i++) {
    uni.uploadFile({
      url: base_URL + "/api/upload/file",
      filePath: lists[i].url,
      name: "file",
      formData: {
        user: "test",
      },
      header: {
        Authorization: uni.getStorageSync("Authorization"),
      },
      success: async (uploadFileRes) => {
        let data = JSON.parse(uploadFileRes.data);
        if (data.code == 200) {
          filelist.splice(fileListLen, 1, {
            ...item,
            status: "success",
            message: "",
            url: data.data.url,
          });
          fileListLen++;
        }
      },
      fail: function (e) {
        uni.hideLoading();
      },
    });

    let item = fileList3.value[fileListLen];
  }
};

selectbankListfun();
async function selectbankListfun() {
  let res = await selectbankList({
    type: 1,
  });
  array.value = res.data;
}
const index = ref(-1);
const array = ref([]);
const bindPickerChange = (e) => {
  index.value = e.detail.value;
  formData.value.name =
    array.value && array.value[index.value].bank_name
      ? array.value[index.value].bank_name
      : "";
};
const formData = ref({});

// 表单数据
const uForm = ref(null);
const nextfun = () => {
  fromdate.value.fileList1 = fileList1.value;
  fromdate.value.fileList2 = fileList2.value;
  fromdate.value.fileList3 = fileList3.value;
  fromdate.value.bank =
    array.value &&
    array.value[index.value] &&
    array.value[index.value].bank_name
      ? array.value[index.value].bank_name
      : fromdate.value.bank;

  uForm.value
    .validate()
    .then(async (valid) => {
      if (valid) {
        fromdate.value.card_z =
          fileList1.value.length > 0 ? fileList1.value[0].url : "";
        fromdate.value.card_f =
          fileList2.value.length > 0 ? fileList2.value[0].url : "";
        fromdate.value.bank_img =
          fileList3.value.length > 0 ? fileList3.value[0].url : "";

        if (!fromdate.value.card_z) {
          uni.$u.toast("请上传身份证正面");
          return;
        }
        if (!fromdate.value.card_f) {
          uni.$u.toast("请上传身份证反面");
          return;
        }
        if (!fromdate.value.bank_img) {
          uni.$u.toast("请上传银行卡正面");
          return;
        }

        try {
          let ress = await userauth({ ...fromdate.value });
          if (ress.code == 200) {
            // thirdPartySignFun();
            uni.$u.toast("提交成功");
            // setTimeout(() => {
            //   uni.navigateTo({
            //     url:
            //       "/pages/servicereward/myreward/auth?url=" + redirectUrl.value,
            //   });
            // }, 500);
            setTimeout(() => {
              uni.redirectTo({
                url: "/pages/servicereward/myreward/realnamepay",
              });
            }, 500);
          }
        } catch (e) {
          uni.$u.toast(e.info);
          // setTimeout(() => {
          //   uni.navigateBack();
          // }, 1000);
          return;
        }
      } else {
        uni.$u.toast("请留意以上必填信息");
      }
    })
    .catch((e) => {
      // 处理验证错误
      uni.$u.toast(e[0].message);
    });
};
const redirectUrl = ref("");
const thirdPartySignFun = async () => {
  try {
    let res = await thirdPartySignApi();
    redirectUrl.value = res.data.redirectUrl;
  } catch (error) {
    uni.showToast({
      title: error.info,
      icon: "none",
    });
  }
};
const authObj = ref({});
const isbank_sn = ref(false);
const isopen_bank = ref(false);
const isali = ref(false);
const iscard_sn = ref(false);
const isbank = ref(false);
async function getAuthFun() {
  let res = await getAuthApi();
  if (res.code == 200) {
    authObj.value = res.data;
    // if (authObj.value.bank_sn) {
    //   isbank_sn.value = true;
    // }
    // if (authObj.value.open_bank) {
    //   isopen_bank.value = true;
    // }
    // if (authObj.value.ali) {
    //   isali.value = true;
    // }
    if (authObj.value && authObj.value.card_sn) {
      iscard_sn.value = true;
    }
    // if (authObj.value.bank) {
    //   isbank.value = true;
    // }

    if (authObj.value) {
      fromdate.value.bank =
        authObj.value && authObj.value.bank ? authObj.value.bank : "";
      fromdate.value.card_sn =
        authObj.value && authObj.value.card_sn ? authObj.value.card_sn : "";
      fromdate.value.bank_sn =
        authObj.value && authObj.value.bank_sn ? authObj.value.bank_sn : "";
      fromdate.value.open_bank =
        authObj.value && authObj.value.open_bank ? authObj.value.open_bank : "";
      fromdate.value.ali =
        authObj.value && authObj.value.ali ? authObj.value.ali : "";

      fileList1.value = [
        {
          url:
            authObj.value && authObj.value.card_z ? authObj.value.card_z : "",
        },
      ];
      fileList2.value = [
        {
          url:
            authObj.value && authObj.value.card_f ? authObj.value.card_f : "",
        },
      ];
      fileList3.value = [
        {
          url:
            authObj.value && authObj.value.bank_img
              ? authObj.value.bank_img
              : "",
        },
      ];
    }
  } else {
    uni.showToast({
      title: res.info,
      icon: "none",
    });
  }
}
</script>

<template>
  <view class="realname">
    <view class="info-circle-ts">
      <text
        >提现结算由第三方财务管理平台进行结算与发放，需收集您的实名信息用于身份验证、涉税事务申报等用途。</text
      >
    </view>

    <view>
      <u--form
        labelPosition="left"
        :model="fromdate"
        :rules="rules"
        ref="uForm"
        labelWidth="80"
      >
        <view>
          <view class="user-form">
            <u-form-item label=" 实名认证信息" borderBottom ref="item1">
            </u-form-item>
            <u-form-item
              required="true"
              label="姓名"
              prop="name"
              borderBottom
              ref="item1"
            >
              <!-- :disabled="isname ? true : false" -->
              <u--input
                v-model="fromdate.name"
                border="none"
                placeholder="请填写"
              ></u--input>
            </u-form-item>
            <u-form-item
              required="true"
              label="手机号"
              prop="phone"
              borderBottom
              ref="item1"
            >
              <!-- :disabled="isphone ? true : false" -->
              <u--input
                v-model="fromdate.phone"
                border="none"
                placeholder="请填写"
              ></u--input>
            </u-form-item>

            <view class="item-line">
              <u-form-item
                required="true"
                label="身份证号"
                prop="card_sn"
                borderBottom
                ref="item1"
              >
                <!-- :disabled="iscard_sn ? true : false" -->
                <u--input
                  v-model="fromdate.card_sn"
                  border="none"
                  placeholder="请填写"
                ></u--input>
              </u-form-item>
            </view>
          </view>

          <view class="uplade">
            <view class="uplade-title"><text>上传身份证照片</text> </view>
            <view class="uplade-up">
              <up-upload
                :fileList="fileList1"
                @afterRead="
                  (val) => {
                    afterRead1(val, 1);
                  }
                "
                @delete="
                  (val) => {
                    deletePic1(val, 1);
                  }
                "
                name="1"
                multiple
                :maxCount="1"
                width="250"
                height="150"
              >
                <image
                  src="@/pages/servicereward/static/icon-4.png"
                  mode="widthFix"
                  style="width: 254rpx; height: 180rpx;"
                ></image>
                <view class="upload-list">正面（人像）</view>
              </up-upload>
              <up-upload
                :fileList="fileList2"
                @afterRead="
                  (val) => {
                    afterRead2(val, 2);
                  }
                "
                @delete="
                  (val) => {
                    deletePic2(val, 2);
                  }
                "
                name="2"
                multiple
                :maxCount="1"
                width="250"
                height="150"
              >
                <image
                  src="@/pages/servicereward/static/icon-2.png"
                  mode="widthFix"
                  style="width: 254rpx; height: 180rpx;"
                ></image>
                <view class="upload-list">反面（国徽）</view>
              </up-upload>
            </view>
          </view>
        </view>
        <view>
          <view class="user-form">
            <u-form-item
              label="银行卡信息"
              borderBottom
              ref="item1"
            ></u-form-item>

            <u-form-item
              required="true"
              label="银行卡号"
              prop="bank_sn"
              borderBottom
              ref="item1"
            >
              <!-- :disabled="isbank_sn ? true : false" -->
              <u--input
                v-model="fromdate.bank_sn"
                border="none"
                placeholder="请填写16位银行卡号"
              ></u--input>
            </u-form-item>

            <u-form-item name="name" label="银行名称">
              <picker
                @change="bindPickerChange"
                :value="index"
                :range="array"
                range-key="bank_name"
              >
                <!-- :disabled="isbank ? true : false" -->

                <view class="uni-input select-uni-input" v-if="index >= 0"
                  >{{ array[index].bank_name }}
                </view>
                <view
                  :class="fromdate.bank ? 'uni-input' : ''"
                  v-if="index < 0"
                >
                  {{ fromdate.bank ? fromdate.bank : "请选择" }}
                </view>
              </picker>
            </u-form-item>

            <view class="item-line">
              <u-form-item
                required="true"
                label="开户支行"
                prop="open_bank"
                borderBottom
                ref="item1"
              >
                <!-- :disabled="isopen_bank ? true : false" -->
                <u--input
                  v-model="fromdate.open_bank"
                  border="none"
                  placeholder="如：中国银行四川成都双流支行"
                ></u--input>
              </u-form-item>
            </view>
          </view>

          <view class="uplade">
            <view class="uplade-title"><text>上传银行卡照片</text> </view>
            <view class="uplade-up">
              <up-upload
                :fileList="fileList3"
                @afterRead="
                  (val) => {
                    afterRead3(val, 1);
                  }
                "
                @delete="
                  (val) => {
                    deletePic3(val, 1);
                  }
                "
                name="1"
                multiple
                :maxCount="1"
                width="250"
                height="150"
              >
                <image
                  src="@/pages/servicereward/static/bank.png"
                  mode="widthFix"
                  style="width: 254rpx; height: 180rpx;"
                ></image>
                <view class="upload-list">正面（卡号）</view>
              </up-upload>
            </view>
          </view>
        </view>

        <view>
          <view class="user-form">
            <u-form-item
              label=" 支付宝信息"
              borderBottom
              ref="item1"
            ></u-form-item>
            <view class="item-line">
              <u-form-item
                required="true"
                label="支付宝账号"
                prop="ali"
                borderBottom
                ref="item1"
              >
                <!-- :disabled="isali ? true : false" -->

                <u--input
                  v-model="fromdate.ali"
                  border="none"
                  placeholder="请填写"
                ></u--input>
              </u-form-item>
            </view>
          </view>
        </view>
      </u--form>
    </view>

    <view class="foodr-bt">
      <view class="bt-sbuit" @click="nextfun">提交认证</view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import "realname.scss";
</style>
